package com.nutricia.biz.impl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

//import com.netflix.infix.lang.infix.antlr.EventFilterParser.null_predicate_return;
import com.nutricia.biz.convertor.SystemMenuConvertor;
//import com.nutricia.biz.convertor.SystemUserConvertor;
import com.nutricia.common.api.SystemUserFacade;
//import com.nutricia.common.api.enums.PermissionCodeEnums;
import com.nutricia.common.api.enums.UserLoginNameEnums;
import com.nutricia.common.api.enums.UserStateEnums;
import com.nutricia.common.api.info.CmsMenuInfo;
//import com.nutricia.common.api.info.PageInfo;
import com.nutricia.common.api.info.SystemUserBaseInfo;
//import com.nutricia.common.api.info.SystemUserInfo;
import com.nutricia.common.api.request.CreateSystemUserReq;
import com.nutricia.common.api.request.CurrentLoginUserRequest;
import com.nutricia.common.api.request.GetUserAndRoleReq;
//import com.nutricia.common.api.request.GetUserByPermissionCodeReq;
import com.nutricia.common.api.request.GetUserNameReq;
import com.nutricia.common.api.request.LoginReq;
//import com.nutricia.common.api.request.PageGetSystemUserReq;
import com.nutricia.common.api.request.UpdateSystemUserReq;
import com.nutricia.common.api.request.UpdateSystemUserStateReq;
import com.nutricia.common.api.result.CreateSystemUserRes;
import com.nutricia.common.api.result.GetUserAndRoleRes;
//import com.nutricia.common.api.result.GetUserByPermissionCodeRes;
import com.nutricia.common.api.result.GetUserNameRes;
import com.nutricia.common.api.result.GetUserPermissionAndMenuRes;
import com.nutricia.common.api.result.LoginRes;
//import com.nutricia.common.api.result.PageGetSystemUserRes;
import com.nutricia.common.api.result.UpdateSystemUserRes;
import com.nutricia.common.api.result.UpdateSystemUserStateRes;
//import com.nutricia.common.condition.PageQueryUserCondition;
import com.nutricia.common.lang.ServiceCallBack;
import com.nutricia.common.util.CheckUtil;
import com.nutricia.core.ex.BizErrorCode;
import com.nutricia.core.model.domain.SystemUserDO;

/**
 * 系统用户
 *
 * @author: huangsheng
 * @date: 2017/10/24
 */
@Service("systemUserFacade")
public class SystemUserFacadeImpl extends AbstractFacadeImpl implements SystemUserFacade {

    /**
     * 登入CMS接口
     *
     * @param loginReq 登入相关类
     */
    public LoginRes login(@RequestBody LoginReq loginReq) {
        logger.info("用户登入--Login");
        final LoginRes result = new LoginRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                CheckUtil.isNotBlank(loginReq.getUserLoginName(), "userLoginName为空");
                CheckUtil.isNotBlank(loginReq.getPassword(), "password为空");
                logger.info("用户登入：userLoginName = {}", loginReq.getUserLoginName());
            }

            @Override
            public void doService() throws Exception {
                String userId = systemUserService.login(loginReq.getUserLoginName(), loginReq.getPassword(), loginReq.getLoginIp());
                logger.info("用户登入成功，userId = {}", userId);
                result.setUserId(userId);
                result.setSuccess(true);
            }

        });
    }

//    /**
//     * 分页获取系统用户数据
//     *
//     * @author: huangsheng
//     * @date: 2017/10/19 下午5:21
//     */
//    public PageGetSystemUserRes pageGetSystemUser(@RequestBody PageGetSystemUserReq pageGetSystemUserReq) {
//        logger.info("分页获取系统用户数据--PageGetSystemUser");
//        final PageGetSystemUserRes result = new PageGetSystemUserRes();
//        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
//            @Override
//            public void check() throws Exception {
//
//                CheckUtil.isTrue(pageGetSystemUserReq.getPageIndex() > 0, BizErrorCode.PARAM_ERROR, "页数小于等于0");
//                logger.info("pageSize = {}, pageIndex = {}", pageGetSystemUserReq.getPageSize(), pageGetSystemUserReq.getPageIndex());
//            }
//
//            @Override
//            public void doService() throws Exception {
//
//                PageQueryUserCondition pageQueryUserCondition =
//                        new PageQueryUserCondition(pageGetSystemUserReq.getPageIndex(), pageGetSystemUserReq.getPageSize());
//                pageQueryUserCondition.setUserLoginName(pageGetSystemUserReq.getUserLoginName());
//                pageQueryUserCondition.setUserName(pageGetSystemUserReq.getUserName());
//                logger.info("查询参数：userLoginName = {}, userName = {}", pageGetSystemUserReq.getUserLoginName(), pageGetSystemUserReq.getUserName());
//
//                PageInfo<SystemUserDO> systemUserDOPageInfo = systemUserService.pageGetSystemUser(pageQueryUserCondition);
//                logger.info("获取到数据数量= {}， pageSize = {}， page = {}",
//                        systemUserDOPageInfo.getData() != null ? systemUserDOPageInfo.getData().size() : "0",
//                        systemUserDOPageInfo.getPageSize(), systemUserDOPageInfo.getCurrentPage());
//
//                PageInfo<SystemUserInfo> systemUserInfoPageInfo = new PageInfo<>(pageGetSystemUserReq.getPageSize(), pageGetSystemUserReq.getPageIndex());
//                systemUserInfoPageInfo.setRecordsTotal(systemUserDOPageInfo.getRecordsTotal());
//                systemUserInfoPageInfo.setData(SystemUserConvertor.convertToInfos(systemUserDOPageInfo.getData()));
//
//                result.setUserInfoPageInfo(systemUserInfoPageInfo);
//                result.setSuccess(true);
//            }
//
//        });
//    }

    /**
     * 创建用户
     *
     * @author: huangsheng
     * @date: 2017/10/25 下午1:45
     */
    public CreateSystemUserRes createSystemUser(
            @RequestBody CreateSystemUserReq createSystemUserReq) {
        logger.info("创建用户--createSystemUser");
        final CreateSystemUserRes result = new CreateSystemUserRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                CheckUtil.isNotBlank(createSystemUserReq.getUserLoginName(), "userLoginName为空");
                CheckUtil.isNotBlank(createSystemUserReq.getPassword(), "password为空");
                CheckUtil.isNotBlank(createSystemUserReq.getUserName(), "userName为空");
                logger.info("创建用户：userLoginName = {}, 创建人ID = {}", createSystemUserReq.getUserLoginName(), createSystemUserReq.getCurrentUserId());
            }

            @Override
            public void doService() throws Exception {
                SystemUserDO systemUserDO = new SystemUserDO();
                systemUserDO.setUserLoginName(createSystemUserReq.getUserLoginName());
                systemUserDO.setUserName(createSystemUserReq.getUserName());
                systemUserDO.setPassword(createSystemUserReq.getPassword());
                //设置创建人
                systemUserDO.setCreateId(createSystemUserReq.getCurrentUserId());
                systemUserDO.setUserMail(createSystemUserReq.getUserMail());
                String userId = systemUserService.createUser(systemUserDO);
                logger.info("成功创建用户，ID = {}", userId);

                if (CollectionUtils.isNotEmpty(createSystemUserReq.getRoleIds())) {
                    systemUserService.batchCreateUserRole(createSystemUserReq.getRoleIds(), userId);
                }
                result.setUserId(userId);
                result.setSuccess(true);
            }

        });
    }

    /**
     * 获取用户和用户的角色数据
     *
     * @author: huangsheng
     * @date: 2017/10/25 下午1:45
     */
    public GetUserAndRoleRes getUserAndRoleRes(@RequestBody GetUserAndRoleReq getUserAndRoleReq) {
        logger.info("获取用户、用户所有用的角色数据--getUserAndRoleRes");
        final GetUserAndRoleRes result = new GetUserAndRoleRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                CheckUtil.isNotBlank(getUserAndRoleReq.getUserId(), "userId为空");
            }

            @Override
            public void doService() throws Exception {

                SystemUserDO systemUserDO = systemUserService.getUserDOByUserId(getUserAndRoleReq.getUserId());

                SystemUserBaseInfo systemUserBaseInfo = new SystemUserBaseInfo();
                systemUserBaseInfo.setId(systemUserDO.getId());
                systemUserBaseInfo.setUserLoginName(systemUserDO.getUserLoginName());
                systemUserBaseInfo.setUserName(systemUserDO.getUserName());
                systemUserBaseInfo.setUserMail(systemUserDO.getUserMail());

                result.setUserInfo(systemUserBaseInfo);
                result.setRoleIds(systemUserService.getUserRoleIds(getUserAndRoleReq.getUserId()));
                result.setSuccess(true);
            }

        });
    }

    /**
     * 更新用户数据
     *
     * @author: huangsheng
     * @date: 2017/10/25 下午5:37
     */
    public UpdateSystemUserRes updateSystemUser(
            @RequestBody UpdateSystemUserReq updateSystemUserReq) {
        logger.info("创建用户--updateSystemUser");
        final UpdateSystemUserRes result = new UpdateSystemUserRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

                CheckUtil.isNotBlank(updateSystemUserReq.getUserId(), "userId为空");
                CheckUtil.isNotBlank(updateSystemUserReq.getUserLoginName(), "userLoginName为空");
                CheckUtil.isNotBlank(updateSystemUserReq.getUserName(), "userName为空");
                logger.info("修改数据：{}，修改人ID = {}", updateSystemUserReq.getUserId(), updateSystemUserReq.getCurrentUserId());
            }

            @Override
            public void doService() throws Exception {
                SystemUserDO systemUserDO = new SystemUserDO();
                systemUserDO.setId(updateSystemUserReq.getUserId());
                systemUserDO.setUserLoginName(updateSystemUserReq.getUserLoginName());
                systemUserDO.setUserName(updateSystemUserReq.getUserName());
                systemUserDO.setPassword(updateSystemUserReq.getPassword());
                systemUserDO.setUserMail(updateSystemUserReq.getUserMail());
                //设置修改人
                systemUserDO.setModifyId(updateSystemUserReq.getCurrentUserId());

                String userId = systemUserService.updateUser(updateSystemUserReq.getRoleIds(), systemUserDO);
                logger.info("成功更新用户，ID = {}", userId);
                result.setUserId(userId);
                result.setSuccess(true);
            }

        });
    }

    /**
     * 禁用、启用用户
     *
     * @author: huangsheng
     * @date: 2017/10/25 下午5:38
     */
    public UpdateSystemUserStateRes disableOrEnable(@RequestBody UpdateSystemUserStateReq updateSystemUserStateReq) {
        logger.info("禁用、启用用户--disableOrEnable");
        final UpdateSystemUserStateRes result = new UpdateSystemUserStateRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

            	CheckUtil.isNotBlank(updateSystemUserStateReq.getUserId(), "userId为空");
                String userState = updateSystemUserStateReq.getUserState();
                logger.info("操作：{}, 修改人ID = {}", userState, updateSystemUserStateReq.getCurrentUserId());
                CheckUtil.isNotBlank(userState, "userState为空");
                CheckUtil.isTrue(UserStateEnums.isInclude(userState), BizErrorCode.PARAM_ERROR, "userState");
            }

            @Override
            public void doService() throws Exception {
                systemUserService.updateUserState(
                        updateSystemUserStateReq.getUserState(), updateSystemUserStateReq.getUserId(), updateSystemUserStateReq.getCurrentUserId());
                result.setUserId(updateSystemUserStateReq.getUserId());
                result.setSuccess(true);
            }

        });
    }


    /**
     * 获取用户的权限和权限下的menu数据
     *
     * @author: huangsheng
     * @date: 2017/10/25 下午5:38
     */
    public GetUserPermissionAndMenuRes getUserPermissionAndMenu(@RequestBody CurrentLoginUserRequest currentLoginUserRequest) {
        logger.info("获取用户的权限和权限下的menu数据--getUserPermissionAndMenu");
        final GetUserPermissionAndMenuRes result = new GetUserPermissionAndMenuRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {

            	CheckUtil.isNotBlank(currentLoginUserRequest.getCurrentUserId(), "currentUserId为空");
                logger.info("获取用户ID = {} 的菜单和权限数据", currentLoginUserRequest.getCurrentUserId());
            }

            @Override
            public void doService() throws Exception {
                SystemUserDO systemUserDO = systemUserService.getUserDOByUserId(currentLoginUserRequest.getCurrentUserId());
                CheckUtil.isTrue(null != systemUserDO,BizErrorCode.USER_IS_NOE_EXIST, "用户不存在");
                logger.info("获取到用户，loginName = {}", systemUserDO.getUserLoginName());

                SystemUserBaseInfo systemUserBaseInfo = new SystemUserBaseInfo();
                systemUserBaseInfo.setId(systemUserDO.getId());
                systemUserBaseInfo.setUserLoginName(systemUserDO.getUserLoginName());
                systemUserBaseInfo.setUserName(systemUserDO.getUserName());
                result.setUserInfo(systemUserBaseInfo);

                // 获取用户菜单数据
                List<CmsMenuInfo> cmsMenuInfos = SystemMenuConvertor.convertToCmsMenuInfos(
                        systemUserService.getUserMenuList(systemUserDO.getUserLoginName(), currentLoginUserRequest.getCurrentUserId()));
                result.setMenus(cmsMenuInfos);

                if (StringUtils.equals(UserLoginNameEnums.ADMIN.getKey(), systemUserDO.getUserLoginName())) {
                    logger.info("当前用户为admin，不查询权限数据");
                    result.setUserCode(UserLoginNameEnums.ADMIN.getKey());
                    result.setPermissionCodes(systemPermissionService.getAllSystemPermission());
                } else {
                    logger.info("当前用户不是admin，查询权限数据");
                    if (CollectionUtils.isNotEmpty(cmsMenuInfos)) {
                        List<String> permissionCodes = systemUserService.getUserPermissionCodes(currentLoginUserRequest.getCurrentUserId());
                        logger.info("用户拥有 {} 条权限", permissionCodes.size());
                        result.setPermissionCodes(permissionCodes);
                    }
                }
                result.setSuccess(true);
            }

        });
    }


    /**
     * 通过userId获得userName
     * @param getUserNameReq
     * @return
     */
    public GetUserNameRes getUserNameById(@RequestBody GetUserNameReq getUserNameReq){
        final GetUserNameRes result = new GetUserNameRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
            	CheckUtil.isNotBlank(getUserNameReq.getUserId(), "用户ID为空");

            }

            @Override
            public void doService() throws Exception {
                String userName = systemUserService.getUserNameById(getUserNameReq.getUserId());
                logger.info("获取到用户名字： {} ", userName);
                GetUserNameRes getUserNameRes = new GetUserNameRes();
                getUserNameRes.setUserName(userName);
                result.setUserName(userName);
                result.setSuccess(true);
            }

        });
    }
}
